<?php

/**
 * This file is part of the Pagizer package.
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 *
 * @copyright   Copyright (c) 2010 Advisa (http://www.advisa.fr)
 * @author      Pagizer Core Team <team@pagizer.org>
 * @package     pagizer
 * @subpackage  medias
 */

class m_medias_actions_AjaxDuplicateMediaAction extends m_backoffice_extends_Action
{
	public function execute()
	{
            $row = $this->getRequestParameter("row");
            $id = is_array($row) ? $row[0] : $row;

            $originalPublication = $this->getDocumentProvider()->getByUniqueId($id, $this->getContextLang());
            $formValues = $this->getFormValues("form");
            $errors = array();

            if(count($formValues) > 0)
            {
                if($formValues['label'] == "")
                {
                    $errors["label"] = $this->getLocale('backoffice.errors.required');
                }
                else
                {
                    $parent = $this->getDocumentProvider()->getByUniqueId($formValues['folder']);
                    $errors["exist"] = $this->duplicatePublication($formValues, $originalPublication,$parent);

                    if(is_bool($errors["exist"]) && $errors["exist"] == true)
                    {
                        $this->addToModel("destPublication", $originalPublication);
                        $errors["status"] = "success";
                        $errors["dest"] = $parent->getEditUrl($parent->getLang());
                    }
                }

                $this->addToModel("errors", $errors);
            }

            if(!isset($errors['status']))
            {
                $values["label"]   = "(copie)".$originalPublication->getLabel();
                $values["folders"] = m_backoffice_services_TreeService::getInstance()->getSelectArray("medias", array("modules_backoffice/Folder"), null, false, true, 'medias', 'add');
                $values["folder"]  = $originalPublication->getDocumentParent()->getLabel();
                $this->addToModel("values", $values);
            }

            $this->addToModel("values", $values);
            $this->addToModel("originalPublication", $originalPublication);

            $this->addToModel("destPublication", $originalPublication);
            $this->setView('success');
	}	
	
	public function validate()
	{
		return $this->getUserContext()->hasRight(array("backoffice_accessBo", "medias_Edit"));
	}

	private function duplicatePublication($formValues, $originalPub,$parent=null)
	{
            $destPublication = $originalPub->cloneToNew();
            if($parent==null)
            {
                $parent = $this->getParent($originalPub);
            }

            $result = $this->getDocumentProvider()->loadDocuments($originalPub->getDocumentModel())->isChildOf($parent->getUniqueId())->whereIsEqual("document_label", $formValues['label'])->count();

            if($result > 0)
            {
                return $this->getLocale('medias.locales.fileExist', null, array('file' => $formValues['label']));
            }
            
            $destPublication->setPublicationStatus("DRAFT")->setAuthor($this->getUser()->getLogin())->setLabel($formValues['label']);
            $destPublication->save(false);
            $parent->addMedia($destPublication)->save();

            $NewfileName = $destPublication->getFilePath().$destPublication->getFileNameWoExt().".".$destPublication->getExtension();
            $OldfileName = $originalPub->getFilePath().$originalPub->getFileNameWoExt().".".$originalPub->getExtension();
            if(file_exists($OldfileName)&&!file_exists($NewfileName)&&$OldfileName!=""&&$NewfileName!="")
            {
                if(!is_dir($destPublication->getFilePath()))
                {
                    mkdir($destPublication->getFilePath(), 0777, true);
                }
                copy($OldfileName,$NewfileName);
            }
            $destPublication->createIcon();
            $destPublication->createMceIcon();
            $destPublication->createPreview();
            return true;
	}

	private function getParent($document)
	{
		return f_relation_Manager::getInstance($document)->getParents()->withLang($document->getLang())->retrieveDocuments();
	}
}